package org.sol.language.parser.internal;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

import org.antlr.runtime.ANTLRReaderStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.tree.CommonTree;
import org.sol.language.parser.ISolParser;
import org.sol.language.parser.grammar.SolLexer;
import org.sol.language.parser.grammar.SolParser;
import org.sol.language.parser.grammar.SolParser.module_return;

public class SolParserImpl implements ISolParser {

	public boolean parseFile(String filePath) {
		try {
			Reader reader = new FileReader(filePath);
			boolean result = parse(reader);
			reader.close();
			return result;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public boolean parseString(String expression) {
		try {
			Reader reader = new StringReader(expression);
			boolean result = parse(reader);
			reader.close();
			return result;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	private boolean parse(Reader reader) {
		try {
			SolLexer lexer = new SolLexer(new ANTLRReaderStream(reader));
			CommonTokenStream tokens = new CommonTokenStream(lexer);
			SolParser parser = new SolParser(tokens);
			module_return result = parser.module();
			CommonTree tree = (CommonTree) result.getTree();
			return (tree.isNil() == false);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RecognitionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
}
